/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test_system.user_logic;

import test_system.parser.ParserCSV;

/**
 * Class to declarate user session
 *
 * @author root
 */
public class Session {

    private static final String USER_FILE = "users.txt";
    private User user;

    public boolean isAdmin() {
        return user.isAdmin();
    }
    
    

    public static Session createSession(String login, String pass) {
        String[][] usersData = getUsersData();
        int index = checkAvtData(login, pass, usersData);
        if (index == -1) {
            System.out.println("Avtorization failed. \n Try again.");
            return null;
        }
        if (usersData[index][3].equals("admin")) {
            User user = new Admin(usersData[index][0], usersData[index][1],
                    usersData[index][2]);
            return new Session(user);
        } else {
            User user = new Student(usersData[index][0], usersData[index][1],
                    usersData[index][2], usersData[index][3]);
            return new Session(user);
        }

    }


    private static int checkAvtData(String login, String pass, String[][] regUsersAvtData) {
        for (int i = 0; i < regUsersAvtData.length; i++) {
            if (login.equals(regUsersAvtData[i][0]) && pass.equals(regUsersAvtData[i][1])) {
                return i;
            }
        }
        return -1;
    }

    private static String[][] getUsersData() {
        ParserCSV parser = new ParserCSV();
        StringBuffer parseResult = parser.parseFile(USER_FILE);
        String[] lineArr = parseResult.toString().split(";");
        String[][] regUsersAvtData = new String[lineArr.length][4];
        for (int i = 0; i < lineArr.length; i++) {
            regUsersAvtData[i] = lineArr[i].split(",");
        }

        return regUsersAvtData;
    }

    private Session(User user) {
        this.user = user;
    }

    public User getUser() {
        return user;
    }

}
